package com.tpo.jnotes.client.layer.model.layer;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.tpo.jnotes.client.layer.model.entity.ENote;
import com.tpo.jnotes.client.layer.model.entity.EntitiesEnum;
import com.tpo.jnotes.client.layer.model.entity.EntityFactory;
import com.tpo.jnotes.client.layer.model.entity.IEntity;
import com.tpo.jnotes.client.layer.model.hibernate.restrictions.DataLayerFilter;
import com.tpo.jnotes.client.layer.model.util.HibernateUtil;
import com.tpo.jnotes.client.lib.exception.EntityClassNotFoundException;
import com.tpo.jnotes.client.lib.interfaces.IModelEntity;


public class DataLayer implements IDataLayer {
 
  public DataLayer(){
  }

  private List<IEntity> doQuery(Class<? extends IModelEntity> class1, DataLayerFilter filter) {    
    Session session = HibernateUtil.getSession();
    Criteria criteria = session.createCriteria(class1);
   
    if (filter != null)
      criteria.add(Restrictions.like("RO", "A%").ignoreCase());
   
    List<IEntity> subsList = criteria.list();
    return subsList;
  }
 
  public List<IEntity> getEntityList(EntitiesEnum entityType) throws EntityClassNotFoundException {
    return doQuery(EntityFactory.getEntityClass(entityType), null);
  }

  public List<IEntity> getEntityList(EntitiesEnum entityType, DataLayerFilter filter) throws EntityClassNotFoundException {
    return doQuery(EntityFactory.getEntityClass(entityType), filter);
  }

 
  public void addEntity(IEntity entity) {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    ENote newSub = new ENote();
    session.createQuery("delete from ESub sub").executeUpdate();
    session.save(newSub);
    session.flush();
    tx.commit();
    session.close();
  }
}
